<template>
  <div>
    <TopBar ref="topBar" :tabName="attrs.tabName" :backValue="backValue">
      <template #operate v-if="!isView">
        <el-button :loading="loading" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="save">保存</el-button>
      </template>
    </TopBar>
    <div class="content" v-loading="loading">
      <div class="btn-opea">
        <el-radio-group v-model="moduleType">
          <el-radio-button v-for="(value,key) in moduleTypeEnum" :key="key" :label="value" />
        </el-radio-group>
      </div>
      <BaseInfoForm v-model:customAttributes="customAttribute" @changeSalesStatus="changeSalesStatus" :isView="isView" ref="baseInfoForm" v-show="moduleType === moduleTypeEnum['BASE_INFO']"></BaseInfoForm>
      <MallInfoForm :salesState="salesState" :isView="isView" ref="mallInfoForm" v-show="moduleType === moduleTypeEnum['MALL_INFO']"></MallInfoForm>
      <WholesaleInfoForm :isView="isView" ref="wholesaleInfoForm" v-show="moduleType === moduleTypeEnum['WHOLESALE_INFO']"></WholesaleInfoForm>
    </div>
  </div>
</template>

<script setup>
import { useTableRefresh,useBatchTextFilter } from '@/hooks/index'
import useDiffValue from '../Hooks/useDiffValue'
import { useCommonData } from '../Hooks/index'
import { saveProduct, getProductDetail } from '@/api/ShopDatabase/index'
import TopBar from '@/components/Topbar/index.vue';
import BaseInfoForm from './BaseInfoForm.vue';
import MallInfoForm from './MallInfoForm.vue';
import WholesaleInfoForm from './WholesaleInfoForm.vue';
import { getAllCommodityExtraAttributes } from '@/api/ShopDatabase/goodsSetting'
import useNowCloseTag from '@/hooks/useNowCloseTag'

const props = defineProps({
  isEdit: {
    type: Boolean,
    default: false,
  },
  isView: {
    type: Boolean,
    default: false,
  },
  details: {
    type: Object,
    default: () => ({})
  },
  uuid: {
    type: String,
    default: ''
  }
})

const backValue = '/engageManagement/shopDatabase/productManagement/productManagementIndex'
const { seachTableRef } = useCommonData();
const attrs = useAttrs();
const topBar = ref();
const loading = ref(false);
const pageUuid = ref('');

onActivated(async () => {
  try {
    loading.value = true;
    await getCustomAttribute();
    // 详情查看的情况下每次获取最新的详情，编辑情况下不需要
    if(props.isView){
      if (props.uuid !== pageUuid.value && props.uuid){
        moduleType.value = moduleTypeEnum['BASE_INFO'];
      }
      await getDetails();
    }else{
      if (props.uuid !== pageUuid.value && props.uuid) {
        moduleType.value = moduleTypeEnum['BASE_INFO'];
        baseInfoForm.value.formRef.resetFields();
        mallInfoForm.value.formRef.resetFields();
        wholesaleInfoForm.value.formRef.resetFields();
        await getDetails();
      }
    }
  } finally {
    loading.value = false;
  }
})

const customAttribute = ref([]);
// 获取产品自定义属性列表
async function getCustomAttribute() {
  const res = await getAllCommodityExtraAttributes()
  customAttribute.value = res.productAttributesList.filter(item => item.disabled!==1).map(item => {
    return {
      extraAttributesId: item.id,
      sourceType: item.sourceType,
      extraAttributesName: item.fieldName,
      fieldType: item.fieldType,
      extraAttributesValue: customAttribute.value.find(i => i.extraAttributesId === item.id)?.extraAttributesValue ?? null,
      optionContent: item.optionContent.split(',').filter(item=>item),
    }
  })
}

// 编辑时用于比较是否变化的值
let oldDetails = {}
const getDetails = async () => {
  const res = await getProductDetail(props.uuid);
  pageUuid.value = res.id;
  oldDetails = {
    retailPrice: +res.retailPrice,
    wholesalePrice: +res.wholesaleInfoPrice,
    salesStatus: +res.salesState,
    wholesaleStatus: +res.wholesaleInfoState,
  }
  salesState.value = +res.salesState;
  baseInfoForm.value.form.code = res.code;
  baseInfoForm.value.form.name = res.productName;
  baseInfoForm.value.form.specification = res.specification;
  baseInfoForm.value.form.placeOrigin = res.origin;
  baseInfoForm.value.form.manufacturer = res.manufacturer;
  baseInfoForm.value.form.type = res.categoryId;
  baseInfoForm.value.form.barCode = res.barcode;
  baseInfoForm.value.form.executiveStandard = res.carriedStandard;
  baseInfoForm.value.form.mnemonicCode = res.mnemonicCode;
  baseInfoForm.value.form.unit = res.unit;
  baseInfoForm.value.form.brand = res.businessBrandId.split(',');
  baseInfoForm.value.form.salesStatus = +res.salesState;
  baseInfoForm.value.form.salesClassification = res.salesClassIdList;
  baseInfoForm.value.form.retailPrice = res.retailPrice;
  baseInfoForm.value.form.latestPurchasePrice = res.latestPurchasePrice;
  baseInfoForm.value.form.minSellingPrice = res.minSellingPrice;
  baseInfoForm.value.tableData[0] = {
    totalDose: res.usageTotalDose,
    unit: res.usageUnit,
    wayUse: res.usageWayOfUse.split(',').filter(item => item !== ''),
    singleDose: res.usageDosa,
    frequencyUse: res.usageFrequency,
    daysUse: res.usageDays,
  }
  mallInfoForm.value.form.allowMall = +res.mallInfoPut;
  mallInfoForm.value.form.detail = res.mallInfoDetails;
  mallInfoForm.value.form.productVideo = res.productVideo;
  mallInfoForm.value.form.mallPlatformFee = res.mallPlatformFee;
  mallInfoForm.value.form.pickType = res.pickType;
  wholesaleInfoForm.value.form.wholesaleStatus = +res.wholesaleInfoState;
  wholesaleInfoForm.value.form.wholesalePrice = res.wholesaleInfoPrice;
  wholesaleInfoForm.value.form.wholesaleClass = res.wholesaleInfoClassification?res.wholesaleInfoClassification.split(','):[];
  wholesaleInfoForm.value.form.minimumOrderQuantity = res.wholesaleInfoMinimumPurchase;
  wholesaleInfoForm.value.form.detail = res.wholesaleInfoDetails;

  baseInfoForm.value.form.imgs = res.productPictureList.map(item => item.url).filter(item => item);
  mallInfoForm.value.form.imgs = res.mallPictureList.map(item => item.url).filter(item => item);
  wholesaleInfoForm.value.form.imgs = res.wholesalePictureList.map(item => item.url).filter(item => item);
  customAttribute.value.forEach(item => {
    const resItem = res.productAttributeList.find(pItem => pItem.extraAttributesId === item.extraAttributesId);
    if (resItem) {
      item.extraAttributesValue = resItem.fieldType === 4 ? resItem.extraAttributesValue ? resItem.extraAttributesValue.split(',') : [] : resItem.extraAttributesValue;
    }
  })
  if(props.isView){
    useBatchTextFilter(baseInfoForm.value.form)
    useBatchTextFilter(mallInfoForm.value.form)
    useBatchTextFilter(wholesaleInfoForm.value.form)
    useBatchTextFilter(baseInfoForm.value.tableData[0])
  }
}

const moduleTypeEnum = {
  'BASE_INFO': '基础信息',
  'MALL_INFO': '商城信息',
  'WHOLESALE_INFO': '批发信息',
}
const moduleType = ref(moduleTypeEnum['BASE_INFO']);

const baseInfoForm = ref();
const mallInfoForm = ref();
const wholesaleInfoForm = ref();
// 处理销售状态变化，同步变化允许上架商城
const salesState = ref(0);
const changeSalesStatus =(val)=>{
  salesState.value = val
  if(val === 2){
    mallInfoForm.value.form.allowMall = val
  }
}
const verificationType = (type)=>{
  moduleType.value = moduleTypeEnum[type];
  ElMessage.error(`${moduleTypeEnum[type]}未填写完整`);
}
const save = async () => {
    const baseInfoFormRef = baseInfoForm.value.formRef;
    const mallInfoFormRef = mallInfoForm.value.formRef;
    const wholesaleInfoFormRef = wholesaleInfoForm.value.formRef;

    const baseInfo = baseInfoForm.value.form;
    const usage = baseInfoForm.value.usage;
    const mallInfo = mallInfoForm.value.form;
    const wholesaleInfo = wholesaleInfoForm.value.form;
    baseInfoFormRef.validate(valid => {
      mallInfoFormRef.validate(valid1 =>{
        wholesaleInfoFormRef.validate(async valid2 =>{
          try{
            if(!valid){
              verificationType('BASE_INFO')
              return
            }
            if(!valid1){
              verificationType('MALL_INFO')
              return
            }
            if(!valid2){
              verificationType('WHOLESALE_INFO')
              return
            }
            if(valid && valid1 && valid2){
              //比较需要二次确认的值
              const newValue = {
                retailPrice: +baseInfo.retailPrice,
                wholesalePrice: +wholesaleInfo.wholesalePrice,
                salesStatus: +baseInfo.salesStatus,
                wholesaleStatus: +wholesaleInfo.wholesaleStatus,
              }
              let isDiff = true
              // 只在编辑时比较
              if(props.isEdit){
                isDiff = await useDiffValue(oldDetails, newValue)
              }
              // 如果取消保存，则不做任何处理
              if(!isDiff && props.isEdit) return
              loading.value = true;
              // 处理图片 sourceType	来源类型（1-产品，2-项目，3-套餐，4-物资，5-商城信息，6-批发信息）
              const picList = [
                ...baseInfo.imgs.map(item =>({
                  sourceType: 1,
                  url: item,
                })),
                ...mallInfo.imgs.map(item =>({
                  sourceType: 5,
                  url: item,
                })),
                ...wholesaleInfo.imgs.map(item =>({
                  sourceType: 6,
                  url: item,
                })),
              ]
              const params = {
                add: props.isEdit ? 0 : 1,
                productName: baseInfo.name,
                specification: baseInfo.specification,
                origin: baseInfo.placeOrigin,
                manufacturer: baseInfo.manufacturer,
                category:baseInfoForm.value.categoryLabel,
                categoryId: baseInfo.type,
                barcode: baseInfo.barCode,
                mnemonicCode: baseInfo.mnemonicCode,
                unit: baseInfo.unit,
                carriedStandard: baseInfo.executiveStandard,
                businessBrandId: baseInfo.brand.join(','),
                salesState: baseInfo.salesStatus,
                salesClass:baseInfoForm.value.salesClassLabel,
                salesClassIdList: baseInfo.salesClassification,
                retailPrice: baseInfo.retailPrice,
                minSellingPrice: baseInfo.minSellingPrice, //最低售价
                latestPurchasePrice: baseInfo.latestPurchasePrice,
                usageTotalDose: usage.totalDose,
                usageUnit: usage.unit,
                usageWayOfUse: usage.wayUse.join(','),
                usageDosa: usage.singleDose,
                usageFrequency: usage.frequencyUse,
                usageDays: usage.daysUse,
                productVideo: mallInfo.productVideo,
                mallPlatformFee: mallInfo.mallPlatformFee,
                mallInfoPut: mallInfo.allowMall,
                mallInfoDetails: mallInfo.detail,
                pickType: mallInfo.pickType,
                wholesaleInfoState: wholesaleInfo.wholesaleStatus,
                wholesaleInfoPrice: wholesaleInfo.wholesalePrice,
                wholesaleInfoClassification: wholesaleInfo.wholesaleClass.join(','),
                wholesaleInfoMinimumPurchase: wholesaleInfo.minimumOrderQuantity,
                wholesaleInfoDetails: wholesaleInfo.detail,
                attributesList: customAttribute.value.map(item => ({
                  ...item,
                  extraAttributesValue: item.fieldType === 4 ? item.extraAttributesValue.join(',') : item.extraAttributesValue,
                  optionContent:item.optionContent.join(',')
                })),//自定义属性
                busiCommodityPictureVoList: picList,//图片
              }
              if (props.isEdit) {
                params.id = props.uuid;
              }
              console.log('params', params)
              await saveProduct(params);
              pageUuid.value = '';
              moduleType.value = moduleTypeEnum['BASE_INFO'];
              ElMessage.success(props.isEdit ? '修改成功' : '新增成功');
              cancel();
              useTableRefresh(seachTableRef, props.isEdit);
            }
          }finally{
            loading.value = false;
          }
        })
      })
    })
}
const reset = () => {
  baseInfoForm.value.reset()
  mallInfoForm.value.reset()
  wholesaleInfoForm.value.reset()
  pageUuid.value = ''
}
useNowCloseTag(reset)
const cancel = () => {
  topBar.value.backHandle()
  reset()
}
</script>

<style lang="less" scoped>
:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid #3480FF;
}

.content {
  padding: 16px 24px;
}
</style>